package onlinebanking.security.probabilistic;

import java.math.BigInteger;
import java.util.Random;

public class GMEncoder {
	
	private GMPublicKey gmPublicKey;
	
	public GMEncoder(GMPublicKey gmPublicKey) {
		this.gmPublicKey = gmPublicKey;
	}
	
	public BigInteger[] encrypt(String message) {
		String binMessage = convertToBinaryMessage(message);
//		System.out.println("Message in Binary: " + binMessage);
		Random r = new Random();

		BigInteger ciphertext[] = new BigInteger[binMessage.length()];
		char msgArr[] = binMessage.toCharArray();
		int length = binMessage.length();

		for (int i = 0; i < length; i++) {
			
			BigInteger random = new BigInteger(gmPublicKey.getModulus().bitLength(), r).mod(gmPublicKey.getModulus()); //dito tumatagal

			if (msgArr[i] == '0') {
				ciphertext[i] = random.multiply(random);
			} else {
				ciphertext[i] = gmPublicKey.getPseudoSquare().multiply(random.multiply(random));
			}
		}
		return ciphertext;
	}
	
	private String convertToBinaryMessage(String message) {
		return new BigInteger(message.getBytes()).toString(2);
	}
}
